/**
 * Copyright (c) 2009-2011, chunquedong(YangJiandong)
 * 
 * This file is part of ChunMap project
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE(Version >=3)
 * 
 * History:
 *     2010-05-05  Jed Young  Creation
 */
package chunmap.app.tools.create;

import java.awt.AWTEvent;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseEvent;

import chunmap.app.bench.AbstractTool;
import chunmap.app.bench.EventType;
import chunmap.model.coord.CoordSeqEditor;
import chunmap.model.coord.Coordinate2D;
import chunmap.model.geom.LineString;
import chunmap.util.CMEventListenerList;

public class LineTool extends AbstractTool {

	private int x = 0;
	private int y = 0;
	private boolean draging = false;

	public Color color = Color.black;
	protected CoordSeqEditor lse = new CoordSeqEditor();
	public CMEventListenerList onCreateFinish=new CMEventListenerList();

	@Override
	public boolean actionEvent(AWTEvent ea, EventType type) {
		if (ea instanceof MouseEvent) {
			MouseEvent e = (MouseEvent) ea;
			if (e.isMetaDown())
				return true;
			if (type == EventType.MouseDown) {
				mousePressed(e);
			} else if (type == EventType.MouseDoubleClick) {
				mouseReleased(e);
			} else if (type == EventType.MouseMove) {
				mouseDragged(e);
			}
			return false;
		}
		return true;
	}

	protected void mouseDragged(MouseEvent e) {
		if (!draging)
			return;

		Image image = map.getBufferImage();
		Graphics tg = map.getBufferGraphics();
		tg.drawImage(map.getOriginImage(), 0, 0, null);

		tg.setColor(color);
		int[] xa=toXa(e.getX());
		int[] ya=toYa(e.getY());
		tg.drawPolyline(xa,ya,xa.length);

		image.flush();
		map.getGraphics().drawImage(image, 0, 0, map);
	}

	protected int[] toXa(int lastX) {
		int[] ps = new int[lse.size() + 1];

		for (int i = 0, n = lse.size(); i < n; i++) {
			double p = map.getView().x2Screen(lse.getPoint(i).getX());
			ps[i] = (int) p;
		}
		ps[lse.size()] = lastX;

		return ps;
	}

	protected int[] toYa(int lastY) {
		int[] ps = new int[lse.size() + 1];

		for (int i = 0, n = lse.size(); i < n; i++) {
			double p = map.getView().y2Screen(lse.getPoint(i).getY());
			ps[i] = (int) p;
		}
		ps[lse.size()] = lastY;

		return ps;
	}

	private void mousePressed(MouseEvent e) {
		draging = true;
		x = e.getX();
		y = e.getY();

		lse.addPointToLast(map.getView().screen2World().convert(
				new Coordinate2D(x, y)));
	}

	private void mouseReleased(MouseEvent e) {
		if (draging) {
			// reset
			draging = false;
			x = 0;
			y = 0;

			lse.deleteOverPoint();
			finished(lse);
			lse = new CoordSeqEditor();
		}
	}

	protected void finished(CoordSeqEditor lse) {
		if (lse.size() > 1) {
			LineString ls = new LineString(lse.toCoordinateSeq());
			onCreateFinish.fire(ls);
		}
	}
}